//
//  HMWelcomeViewController.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/17.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let bottomMargin: CGFloat = 120
private let iconWidth: CGFloat = 85
private let iconHeight: CGFloat = 85

class HMWelcomeViewController: UIViewController {

    private lazy var iconView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "avatar_default_big"))
    
    private lazy var welcomeLabel: UILabel = UILabel(title: "欢饮回来", titleColor: UIColor.darkGray, fontSize: 16)
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
         //自动布局的动画效果应该在 viewDidAppera中执行才会有正确的动画效果
        animate()
    }
    
    private func animate() {
        
        let offsetY = -(UIScreen.main.bounds.height - bottomMargin - iconView.bounds.height)
        
        // 更新约束
        iconView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(offsetY)
        }
        
        // 动画
        UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 7, options: [], animations: {
            
            self.view.layoutIfNeeded()
            
        }, completion: { (_) in
            
            UIView.animate(withDuration: 1.0, animations: {
               
                self.welcomeLabel.alpha = 1
                
            }, completion: { (_) in
                
                NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: nil)
            })
        })
    }

    private func setupUI() {
        
        iconView.layer.cornerRadius = iconWidth * 0.5
        iconView.layer.masksToBounds = true
        
        iconView.sd_setImage(with: HMUserAccountViewModel.shared.headUrl, placeholderImage: #imageLiteral(resourceName: "avatar_default_big"))
        
        welcomeLabel.alpha = 0
        
        view.backgroundColor = UIColor.white
        
        view.addSubview(iconView)
        view.addSubview(welcomeLabel)
        
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.bottom.equalTo(view).offset(-bottomMargin)
            make.size.equalTo(CGSize(width: iconWidth, height: iconHeight))
        }
        
        welcomeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(iconView.snp.bottom).offset(20)
            make.centerX.equalTo(iconView)
        }
    }
  
}
